package com.jxbeidou.gateway.service.impl;

import com.jxbeidou.core.cache.CacheService;
import com.jxbeidou.core.constents.CacheConstants;
import com.jxbeidou.gateway.service.ConfigAttributeService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.PathMatcher;

import java.util.List;
import java.util.Map;

/**
 * @program: jxbeidou-basic
 * @ClassName: ConfigAttributeServiceImpl
 * @description: 权限列表获取  <br />
 * 从缓存中获取权限列表数据
 * @author: 杜晓祥
 * @create: 2023-12-28 09:26
 * 版权所有：交信北斗(北京)信息科技有些公司
 */
@Component
@Slf4j
public class ConfigAttributeServiceImpl implements ConfigAttributeService {

    @Resource
    private CacheService cacheService;


    @Override
    public Map<String, List<String>> loadConfigAttribute() {
        Map<String, List<String>> map = cacheService.hGetAllByType(CacheConstants.SYS_LOGIN_AUTHORITY);
        if (ObjectUtils.isEmpty(map)) {
            return null;
        }
        return map;
    }

    @Override
    public boolean validateAuthority(String url, List<String> role) {
        Map<String, List<String>> map = loadConfigAttribute();
        PathMatcher pathMatcher = new AntPathMatcher();
        for (Map.Entry<String, List<String>> stringListEntry : map.entrySet()) {
            if (pathMatcher.match(url, stringListEntry.getKey())) {
                if (CollectionUtils.containsAny(stringListEntry.getValue(), role)) {
                    return true;
                }
            }
        }
        return false;
    }
}
